package com.example.springblog.utils;

import java.security.Key;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;

import com.example.springblog.constants.Constant;
import com.example.springblog.model.UserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JwtUtils {
    private static final long expiration = 1000 * 60 * 3;
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64URL.decode("BXhqD1O0n92Aqaa9cP5RbOR7e0HScvFkoayHZnEUCkQ="));
    public static String  genToken(Map<String,Object> claim) {
        String token = Jwts.builder()
                .setClaims(claim)
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(key)
                .compact();
        return token;
    }

    public static Claims parseToken(String token){
        if (token==null){
            return null;
        }
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        }catch (Exception e){
//            e.printStackTrace();
            log.error("解析token失败, token:"+token);
        }
        return claims;
    }

    public static boolean checkToken(String token) {
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null) return false;
        return true;
    }

    public static Integer getUserInfoFromToken(String token) {
        Claims claims = JwtUtils.parseToken(token);
        if (claims != null) {
            return (Integer)claims.get(Constant.USER_CLAIM_ID);
        }
        return null;
    }

//    public static void main(String[] args) {
//        Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
//        String secreteString = Encoders.BASE64.encode(key.getEncoded());
//        System.out.println(secreteString);
//    }
}
